<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Digit Recognition</title>
    <style>
        canvas {
            border: 1px solid black;
            background-color: black; /* 设置Canvas背景为黑色 */
        }
    </style>
</head>
<body>
<h1>Draw a Digit (0-9)</h1>
<canvas id="canvas" width="280" height="280"></canvas>
<button id="clear">Clear</button>
<button id="predict">Predict</button>
<p id="result"></p>

<script>
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    const clearButton = document.getElementById('clear');
    const predictButton = document.getElementById('predict');
    const resultElement = document.getElementById('result');

    let drawing = false;

    canvas.addEventListener('mousedown', () => {
        drawing = true;
    });

    canvas.addEventListener('mouseup', () => {
        drawing = false;
    });

    canvas.addEventListener('mousemove', (e) => {
        if (!drawing) return;
        ctx.lineWidth = 20;
        ctx.lineCap = 'round';
        ctx.strokeStyle = 'white';
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
        ctx.beginPath();
        ctx.moveTo(e.offsetX, e.offsetY);
    });

    clearButton.addEventListener('click', () => {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    });

    predictButton.addEventListener('click', () => {
        const dataURL = canvas.toDataURL('image/png');
        const formData = new FormData();
        formData.append('image', dataURL);

        fetch('/predict', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                resultElement.textContent = `Predicted Digit: ${data.predicted_digit}`;
            })
            .catch(error => {
                console.error('Error:', error);
            });
    });
</script>
</body>
</html>
